package com.dhkj.circle.ui.activity;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.NfcA;
import android.os.Bundle;
import android.text.InputType;
import android.widget.TextView;

import com.dhkj.circle.R;
import com.dhkj.circle.broadcast.CardEvent;
import com.dhkj.circle.broadcast.TimeEvent;
import com.dhkj.circle.constant.CardConst;
import com.dhkj.circle.constant.SystemConst;
import com.dhkj.circle.db.sqlite.InfoDBSQLite;
import com.dhkj.circle.entity.CardInfo;
import com.dhkj.circle.thread.TimeThread;
import com.dhkj.circle.utils.CheckCardUtils;
import com.dhkj.circle.utils.DateUtils;
import com.dhkj.circle.utils.NFCUtils;
import com.dhkj.circle.utils.QMUIView;
import com.dhkj.circle.utils.SystemUIUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import pl.com.salsoft.sqlitestudioremote.SQLiteStudioService;

import static com.dhkj.circle.ui.AppContext.sLogger;

public class WelcomeActivity extends Activity {
    private NfcAdapter nfcAdapter;    //NFC初始化
    private PendingIntent mPendingIntent;   //绑定mfc
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
    @BindView(R.id.version)
    TextView versionText;

    @BindView(R.id.time)
    TextView textView;
    private int mCurrentDialogStyle = R.style.QMUI_Dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        EventBus.getDefault().register(this);
        init_NFC();
        ButterKnife.bind(this);
        InfoDBSQLite.getInfoDBSQLite().setSQLConst();

        new Thread(new TimeThread()).start();
        //SQLite管理工具，可以使用该工具进行查看数据
        SQLiteStudioService.instance().start(this);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(TimeEvent timeEvent) {
        textView.setText(DateUtils.getNow());
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        SystemUIUtils.setStickFullScreen(getWindow().getDecorView());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO 自动生成的方法存根
        super.onNewIntent(intent);
        NFCUtils.scanNfc(intent, this.getLocalClassName());

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CardEvent cardEvent) {
        if (!WelcomeActivity.this.isFinishing()) {
            int status = NFCUtils.readNFC(this.getLocalClassName());
            if (status == 1) {
                CardInfo cardInfo = NFCUtils.getCardInfo();
                if (cardInfo.zyh != null) {
                    sLogger.d(cardInfo.toString());
                    if (!CheckCardUtils.checkDwmm(cardInfo.dwmm)) {
                        sLogger.d("单位密码不正确");
                        QMUIView.showError(this, "非本单位卡");
                        return;
                    }
                    if (CheckCardUtils.checkGS(String.valueOf(cardInfo.zyh).trim(), String.valueOf(cardInfo.kh))) {
                        sLogger.d("此卡已挂失");
                        QMUIView.showError(this, "此卡已挂失，请联系管理员");
                        return;
                    }

                    CardConst.setCardInfo(cardInfo);
                    Intent intent = new Intent(this, IndexActivity.class);
                    startActivity(intent);
                }
            } else if (status != 10) {
                sLogger.e("错误卡片");
                QMUIView.showError(WelcomeActivity.this, "无效卡");
            }
            if (status == 10) {
                sLogger.d("配置卡");
                showDialog();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 4. 禁止后台唤醒
        nfcAdapter.disableForegroundDispatch(this);
    }

    private void init_NFC() {
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter == null) {
            sLogger.e("NFC", "设备不支持NFC！");

            return;
        }
        if (!nfcAdapter.isEnabled()) {
            sLogger.e("请在系统设置中先启用NFC功能！");
            return;
        }
        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        try {
            ndef.addDataType("*/*");
        } catch (IntentFilter.MalformedMimeTypeException e) {
            throw new RuntimeException("fail", e);
        }
        mFilters = new IntentFilter[]{ndef,};
        mTechLists = new String[][]{new String[]{NfcA.class.getName()}};
//        sLogger.d(TAG, "init_NFC初始化完成!");
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        versionText.setText("version:" + SystemConst.version + "\t机号：" + SystemConst.getDriver_id());
        nfcAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);

    }


    private void showDialog() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(this);
        builder.setTitle("请输入密码")
                .setPlaceholder("请输入密码")
                .setInputType(InputType.TYPE_CLASS_NUMBER)
                .addAction("取消", (dialog, index) -> dialog.dismiss())
                .addAction("确定", (dialog, index) -> {
                    CharSequence text = builder.getEditText().getText();
                    if (text != null && "070610".equals(text.toString())) {

                        Intent intent = new Intent(WelcomeActivity.this, SystemManagerActivity.class);
                        sLogger.d("进入系统基础管理页面");
                        startActivity(intent);
                        dialog.dismiss();
                    } else {
                        QMUIView.showError(this, "请输入正确密码");
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

}
